var express = require('express');
var router = express.Router();
const Query = require('../tools/db')
const { image_url } = require('../config/config')

//获取课程详情
router.get('/course/:cid', async function (req, res, next) {
  let { cid } = req.params;
  if (!cid) {
    next('必须传入课程');
    return;
  }
  //1.查课程
  let sql1 = `SELECT *FROM e_course WHERE cid = '${cid}'`
  let [err1, result1] = await Query(sql1)
  if (err1) {
    next('服务器内部错误');
    return;
  }
  if(!result1.length){
    next('请传入正确的参数');
    return;
  }
  result1[0].image_src = `${image_url}/uploads/course/${result1[0].image_src}`
  //2.根据查课程返回的数据，找到tid，查老师
  let sql2 = `SELECT *FROM e_teacher WHERE tid = '${result1[0].tid}'`
  let [err2, result2] = await Query(sql2);
  if (err2) {
    next('服务器内部错误');
    return;
  }
  result2[0].head_photo_url = `${image_url}/uploads/photo/${result2[0].head_photo_url}`

  //3.视频列表
  let sql3 = `SELECT *FROM e_video WHERE cid = '${cid}' ORDER BY vnum`
  let [err3, result3] = await Query(sql3);
  if (err3) {
    next('服务器内部错误');
    return;
  }
  result3.map((item) => delete item.video_src);
  res.send({
    code: 200,
    msg: '获取成功',
    result: {
      course: result1[0],
      teacher: result2[0],
      videos: result3

    }
  });
});

module.exports = router;
